using System;
using System.Collections.Generic;
using System.IO;

namespace Pronghorn.Core
{
	public class CSharpSkinParser : ISkinParser
	{
		#region Fields

		private readonly IList<ISkinNodeParser> _nodeList = new List<ISkinNodeParser>();
		private readonly ISkinLocator _skinLocator;
		private readonly IList<INodeVisitor> _visitors;

		#endregion Fields

		#region Constructors

		public CSharpSkinParser(ISkinLocator skinLocatorn, IList<INodeVisitor> visitors)
		{
			_skinLocator = skinLocatorn;
			_visitors = visitors;
		}

		#endregion Constructors

		#region Private Methods

		private void closeSkinClass(TextWriter writer)
		{
			writer.WriteLine("}");//close method
			writer.WriteLine("}");//close class
			writer.WriteLine("}");//close namespace
		}

		private void getNodes()
		{
			var lines = _skinLocator.GetSkinLines();
			foreach (var line in lines)
			{
			    _nodeList.Add(new SkinNodeParser(line,_visitors));
			}
		}

		private void parseNodes(TextWriter writer)
		{
			foreach (var node in _nodeList)
			{
			    node.Parse(writer);
			}
		}

		private void startSkinClass(TextWriter writer)
		{
			writer.WriteLine(string.Format("namespace {0}",_skinLocator.GetNameSpace()));
			writer.WriteLine("{");
			var skinType = _skinLocator.GetSkinType();
			writer.WriteLine(string.Format("public class {0} : SkinBase", skinType));
			writer.WriteLine("{");
			writer.WriteLine(string.Format("public {0}(IProngHornSkinContext skinContext, ICollectionRenderer collectionRenderer) : base(skinContext, collectionRenderer)", skinType));
			writer.WriteLine("{}");

			writer.WriteLine("protected override void GenerateHtml(TextWriter writer)");
			writer.WriteLine("{");
		}

		#endregion Private Methods

		#region Public Methods

		public void Parse(TextWriter writer)
		{
			startSkinClass(writer);
			getNodes();
			parseNodes(writer);
			closeSkinClass(writer);
		}

		#endregion Public Methods
	}
}